import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Field, reduxForm } from 'redux-form';
import { FormattedMessage, injectIntl } from 'react-intl';
import { Prompt } from 'react-router-dom';
import {
  TextArea,
  TextField,
  Select,
  Button,
  Col,
  Row
} from '@folio/stripes/components';

function asyncValidate(values, dispatch, props, blurredField) {
  const { httpValidatorInvoke, initialValues } = props;

  if (values[blurredField]) {
    values[blurredField] = values[blurredField].trim();
  }

  const curValue = values[blurredField];

  if (!!initialValues && initialValues.id) {
    const prevValue = initialValues[blurredField];
    if (curValue !== prevValue) {
      return asyncValidateField(blurredField, curValue, httpValidatorInvoke);
    } else {
      return new Promise((resolve, reject) => {
        return resolve();
      });
    }
  } else if (blurredField) {
    const promises = [];

    promises.push(
      asyncValidateField(
        blurredField,
        values[blurredField],
        httpValidatorInvoke
      )
    );
    return Promise.all(promises);
  } else {
    return Promise.all([]);
  }
}

function asyncValidateField(field, value, validator) {
  return new Promise((resolve, reject) => {
    const query = {};
    if (!value) {
      return resolve();
    }
    query[field] = value;

    validator.reset();
    return validator
      .GET({ params: { query: `(isDel = 0 and name = ${query.name})` } })
      .then(result => {
        if (result.totalRecords && result.totalRecords !== 0) {
          const error = {};
          error[field] =  <FormattedMessage id={"ui-party.other.already.exists"}/>;
          // <FormattedMessage id="ui-party.messageTemplate.data.name.error"/>
          return reject(error);
        } else {
          return resolve();
        }
      });
  });
}

function validate(values, props) {
  const errors = {};

  if (!values || !values.name) {
    errors.name =  <FormattedMessage id={"ui-party.errors.missingRequiredField"}/>;
  }

  return errors;
}

class EditForm extends Component {
  constructor(props) {
    super(props);
    this.state = {
      open: true,

      show: false,
      editsStatus: 'success',

    };
  }

  static propTypes = {
    handleSubmit: PropTypes.func.isRequired,
    initialValues: PropTypes.object,
    dictionary: PropTypes.object,
    cleanSearch: PropTypes.func,
    intl: PropTypes.func,
    cancel:PropTypes.func,
    ascriptionNameList:PropTypes.array,
    exitFlag:PropTypes.bool
  };

  render() {
    const footer = (

        <div>
          <Button onClick={this.props.cancel}>
            <FormattedMessage id="ui-party.cancel" />
          </Button>
          <Button buttonStyle="primary" marginBottom0 type="submit">
            <FormattedMessage id="ui-party.saveAndExit" />
          </Button>
        </div>

    );
    const { handleSubmit, intl } = this.props;

    return (
      <Row center="xs" style={{ width: '100%' }}>
        <Col xs={6}>
          <form data-test-form-page id="form-add" onSubmit={handleSubmit}>
            <Field
              component={Select}
              name="parentId"
              label={
                <FormattedMessage id="ui-party.loans.columns.property.parentName" />
              }
              dataOptions={this.props.ascriptionNameList}
            />
            <Field
              component={TextField}
              name="name"
              label={
                <FormattedMessage id="ui-party.loans.columns.property.name" />
              }
              required
            />
            <Field
              component={TextField}
              name="sort"
              label={
                <FormattedMessage id="ui-party.sort" />
              }
              hasClearIcon
              type="number"
              min="1"
              max="9999"
            />

            <Field
              component={TextArea}
              name="remark"
              label={
                <FormattedMessage id="ui-party.loans.columns.property.remark" />
              }
              style={{ height: '150px' }}
            />

            {footer}
          </form>
        </Col>

      </Row>
    );
  }
}

export default injectIntl(
  reduxForm({
    form: 'classifyEditForm',
    validate,
    asyncValidate,
    asyncBlurFields: ['name'],
    navigationCheck: true,
    enableReinitialize: true
  })(EditForm)
);
